<?php

namespace common\components\system;

use Yii;
use common\helpers\ArrayHelper;
use common\models\mongo\SystemLog;

/**
 * Description of AdminLog
 *
 * @author emhome
 */
class OperationRecord extends BaseLogRecord {

    public $modelClass = SystemLog::class;

    public static function afterFind($event) {
        // 具体要记录什么东西，自己来优化$description
    }

    /**
     * 插入操作.
     * @param obj $event
     * @return mixed
     */
    public static function afterInsert($event) {
        $sender = $event->sender;
        if ($sender instanceof \yii\db\ActiveRecord) {
            $description = '';
            $attributes = $sender->attributes;
            ArrayHelper::remove($attributes, 'gis');
            self::log([
                'table' => $sender::tableName(),
                'class' => $sender::className(),
                'type' => SystemLog::TYPE_INSERT,
                'description' => $description,
                'data' => $attributes,
            ]);
        }
    }

    /**
     * 修改操作
     * @param obj $event
     * @return mixed
     */
    public static function afterUpdate($event) {
        $sender = $event->sender;
        if ($sender instanceof \yii\db\ActiveRecord) {
            if (empty($event->changedAttributes)) {
                return;
            }
            $description = '';
            $attributes = $sender->attributes;
            ArrayHelper::remove($attributes, 'gis');
            $data = [
                'old' => $event->changedAttributes,
                'new' => $attributes,
            ];
            self::log([
                'table' => $sender::tableName(),
                'class' => $sender::className(),
                'type' => SystemLog::TYPE_UPDATE,
                'description' => $description,
                'data' => $data,
            ]);
        }
    }

    /**
     * 删除操作.
     * @param obj $event
     * @return mixed
     */
    public static function afterDelete($event) {
        $sender = $event->sender;
        if ($sender instanceof \yii\db\ActiveRecord) {
            $description = '';
            $attributes = $sender->attributes;
            ArrayHelper::remove($attributes, 'gis');
            self::log([
                'table' => $sender::tableName(),
                'class' => $sender::className(),
                'type' => SystemLog::TYPE_DELETE,
                'description' => $description,
                'data' => $attributes,
            ]);
        }
    }

}
